<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use app\components\CHttpWechat;
use app\components\CTools;
use PHPQRCode\Constants;
use PHPQRCode\QRcode;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\ConsoleOutput;
use yii\console\Controller;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class WechatController extends Controller
{
    public $DEBUG = false;

    public $weuuid, $base_uri, $redirect_uri, $sync_url,$uin, $sid, $skey, $pass_ticket, $deviceId, $BaseRequest;
    public $synckeystr, $SyncKey, $User, $MemberList, $ContactList, $GroupList, $GroupMemeberList, $PublicUsersList, $SpecialUsersList;
    public $saveSubFolders, $saveFolder, $autoOpen, $interactive, $syncHost;
    public $autoReplyMode;

    public $appid, $lang, $lastCheckTs, $MemberCount;
    public $SpecialUsers, $TimeOut, $media_count, $cookie;
    public $user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36';

    public $saveKeyFile;
    public function _init()
    {

        $this->base_uri = 'https://wx.qq.com/cgi-bin/mmwebwx-bin';
        $this->redirect_uri = 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage';//
        $this->uin = '';
        $this->sid = '';
        $this->skey = '';
        $this->sync_url ="";
        $this->pass_ticket = '';
        $this->deviceId = 'e' . substr(md5(uniqid()), 2, 15);
        $this->BaseRequest = [];
        $this->synckeystr = '';
        $this->SyncKey = [];
        $this->User = [];
        $this->MemberList = [];
        $this->ContactList = [];  # 好友
        $this->GroupList = [];  # 群组
        $this->GroupMemeberList = [];  # 群友
        $this->PublicUsersList = [];  # 公众号／服务
        $this->SpecialUsersList = [];  # 特殊账号
        $this->autoReplyMode = true;
        $this->syncHost = '';
        $this->user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36';
        $this->interactive = false;
        $this->autoOpen = false;
        $this->saveFolder = \Yii::$app->basePath . "/runtime/wechat/";

        $this->saveSubFolders = ['webwxgeticon' => 'icons', 'webwxgetheadimg' => 'headimgs',
            'webwxgetmsgimg' => 'msgimgs', 'webwxgetvideo' => 'videos', 'webwxgetvoice' => 'voices',
            '_showQRCodeImg' => 'qrcodes'
        ];
        $this->appid = 'wx782c26e4c19acffb';
        $this->lang = 'zh_CN';
        $this->lastCheckTs = time();
        $this->MemberCount = 0;
        $this->SpecialUsers = ['newsapp', 'fmessage', 'filehelper', 'weibo', 'qqmail',
            'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle', 'lbsapp', 'shakeapp',
            'medianote', 'qqfriend', 'readerapp', 'blogapp', 'facebookapp', 'masssendapp',
            'meishiapp', 'feedsapp', 'voip', 'blogappweixin', 'weixin', 'brandsessionholder',
            'weixinreminder', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c', 'officialaccounts',
            'notification_messages', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c', 'wxitil',
            'userexperience_alarm', 'notification_messages'
        ];
        $this->TimeOut = 20;  # 同步??短时间间隔（单位：秒??
        $this->media_count = -1;

        $this->cookie = \Yii::$app->basePath . "/runtime/wechat/cookie/cookey.".time();
        $this->saveKeyFile = \Yii::$app->basePath . "/runtime/wechat/key/key.key.".time();
    }

    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     */
    public function actionIndex()
    {
        $this->_init();
        $this->_echo('[*] 获取UUID');
        $this->_initUuid();
        $this->_echo('[*] UUID:'.$this->weuuid);
        $this->_echo('[*] 正在获取二维码');
        $this->_showQRCodeImg();
        $this->_echo('[*] 请扫描二维码登录 ... ');
        $this->waitForLogin();

        $this->_echo('[*] 开始登录  ... ');
        $this->login();
        $this->_echo('[*] 初始化  ... ');

        while(true){
            sleep(3);
            $res = $this->_webwxinit();
            if(!$res) {
                $this->_echo('[*] 初始化失败  ... ');
            }else{
                $this->_echo('[*] 初始化成功  ... ');
                break;
            }
        }

        $this->_echo('[*] 消息已读  ... ');
        $res = $this->webwxstatusnotify();
        if(!$res){
            $this->_echo('[*] 消息已读失败  ... ');
            exit;
        }

        $this->_echo('[*] 获取联系人  ... ');

        $this->webwxgetcontact();
        $this->_echo(sprintf('[*] 应有 %s 个联系人，读取到联系人 %d 个',
            $this->MemberCount, count($this->MemberList)));
        $this->_echo(sprintf('[*] 共有 %d 个群 | %d 个直接联系人 | %d 个特殊账号 ｜ %d 公众号或服务号', count($this->GroupList),
            count($this->ContactList), count($this->SpecialUsersList), count($this->PublicUsersList)));

        #会话列表
        $this->_webwxbatchgetcontact();

        $this->listenMsgMode();

    }

    private function _webwxinit($first = true)
    {
        $url = sprintf($this->base_uri . '/webwxinit?pass_ticket=%s&skey=%s&r=%s', $this->pass_ticket, $this->skey, time());
        $params = [
            'BaseRequest' => $this->BaseRequest
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);

        $this->SyncKey = $dic['SyncKey'];
        $this->User = $dic['User'];
        # synckey for synccheck
        $tempArr = [];
        if (is_array($this->SyncKey['List'])) {
            foreach ($this->SyncKey['List'] as $val) {
                # code...
                $tempArr[] = "{$val['Key']}_{$val['Val']}";
            }
        } elseif ($first) {
            return $this->_webwxinit(false);
        }
        //$this->skey = $dic['SKey'];
        $this->synckeystr = implode('|', $tempArr);
        //$this->initSave();
        //var_dump($this->synckey);
        return $dic['BaseResponse']['Ret'] == 0;
    }



    protected function waitForLogin()
    {
        $retryTime = 10;
        $tip = 1;

        while ($retryTime > 0) {
            $url = sprintf('https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s', $tip, $this->weuuid, time());
            $data = $this->_curlGet($url);
            preg_match('/window.code=(\d+);/', $data, $pm);
            $code = $pm[1];

            switch ($code) {
                case '201':
                    $tip = 0;
                    $this->_echo("请点击确认登录");
                    break;
                case '200':
                    preg_match('/window.redirect_uri="(https:\/\/(\S+?)\/\S+?)";/', $data, $matches);

                    $this->redirect_uri = $matches[1].'&fun=new';
                    $url = 'https://%s/cgi-bin/mmwebwx-bin';
//                    $this->vbot->config['server.uri.file'] = sprintf($url, 'file.'.$matches[2]);
                    $this->sync_url = sprintf($url, 'webpush.'.$matches[2]);
                    $this->base_uri = sprintf($url, $matches[2]);
                    return;
                case '408':
                    $tip = 1;
                    $retryTime -= 1;
                    sleep(1);
                    break;
                default:
                    $tip = 1;
                    $retryTime -= 1;
                    sleep(1);
                    break;
            }
        }
    }
    public function login()
    {
        $data = $this->_curlGet($this->redirect_uri);
        $array = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        //var_dump($array);
        if (!isset($array['skey']) || !isset($array['wxsid']) || !isset($array['wxuin']) || !isset($array['pass_ticket']))
            return False;
        $this->skey = $array['skey'];
        $this->sid = $array['wxsid'];
        $this->uin = $array['wxuin'];
        $this->pass_ticket = $array['pass_ticket'];

        $this->BaseRequest = [
            'Uin' => intval($this->uin),
            'Sid' => $this->sid,
            'Skey' => $this->skey,
            'DeviceID' => $this->deviceId
        ];
//        $this->initSave();
        return true;
    }

    public function initSave()
    {
        file_put_contents($this->saveKeyFile, json_encode([
            'skey' => $this->skey,
            'sid' => $this->sid,
            'uin' => $this->uin,
            'pass_ticket' => $this->pass_ticket,
            'deviceId' => $this->deviceId
        ]));
    }


    /*状??????知*/
    public function webwxstatusnotify()
    {
        $url = sprintf($this->base_uri . '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s', $this->pass_ticket);
        $params = [
            'BaseRequest' => $this->BaseRequest,
            "Code" => 3,
            "FromUserName" => $this->User['UserName'],
            "ToUserName" => $this->User['UserName'],
            "ClientMsgId" => time()
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);
        return $dic['BaseResponse']['Ret'] == 0;
    }


    /*获取所有联系人*/
    public function webwxgetcontact()
    {

        $url = sprintf($this->base_uri . '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s',
            $this->pass_ticket, $this->skey, time());
        $dic = CHttpWechat::curlPostJson($url,['cookie' => $this->cookie,'user_agent' => $this->user_agent]);


        $this->MemberCount = $dic['MemberCount'] - 1;//把自己减去
        $this->MemberList = $dic['MemberList'];

        if (is_array($this->MemberList)) {
            foreach ($this->MemberList as $key => $Contact) {
                //$this->_echo(sprintf("%s--------%d-------%d----%s",$Contact['UserName'] ,$Contact['VerifyFlag'],$Contact['VerifyFlag']&8,$Contact['VerifyFlag'] & 8 != 0));
                if (in_array($Contact['UserName'], $this->SpecialUsers)) {
                    $this->SpecialUsersList[] = $Contact;# 特殊账号
                } elseif (($Contact['VerifyFlag'] & 8) != 0) {
                    $this->PublicUsersList[] = $Contact;#公众号
                } elseif (strpos($Contact['UserName'], '@@') !== false) {
                    $this->GroupList[] = $Contact;#群组
                } elseif ($Contact['UserName'] == $this->User['UserName']) {

                } else {
                    $this->ContactList[] = $Contact;
                }
            }
        } else {
            return false;
        }


        $key = time();
        file_put_contents(\Yii::$app->basePath . "/runtime/wechat/member/MemberList.json.".$key, var_export($this->MemberList, true), FILE_APPEND);
        file_put_contents(\Yii::$app->basePath . "/runtime/wechat/member/ContactList.json.".$key, var_export($this->ContactList, true), FILE_APPEND);
        file_put_contents(\Yii::$app->basePath . "/runtime/wechat/member/GroupList.json.".$key, var_export($this->GroupList, true), FILE_APPEND);

        return true;
    }

    /**
     * 获取群信息
     * @return bool
     */
    private function _webwxbatchgetcontact()
    {
        $url = sprintf($this->base_uri . '/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s', time(), $this->pass_ticket);
        $List = [];
        foreach ($this->GroupList as $g) {
            # code...
            $List[] = ["UserName" => $g['UserName'], "EncryChatRoomId" => ""];
        }
        $params = [
            'BaseRequest' => $this->BaseRequest,
            "Count" => count($this->GroupList),
            "List" => $List
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);

//        file_put_contents(\Yii::$app->basePath . "/runtime/wechat/groupuser.json",var_export($dic,true));
        # blabla ...
        $ContactList = $dic['ContactList'];
        $ContactCount = $dic['Count'];
        $this->GroupList = $ContactList;


        foreach ($ContactList as $key => $Contact) {
            $MemberList = $Contact['MemberList'];
            foreach ($MemberList as $member)
                $this->GroupMemeberList[] = $member;
        }


        return true;
    }

    /**
     * 开是监听消息
     */
    public function listenMsgMode()
    {
        $this->_echo('[*] 进入消息监听模式 ... 成功');


        while (true) {
            $this->lastCheckTs = time();
            list($retcode, $selector) = $this->synccheck();
            if ($this->DEBUG) {
                $this->_echo(sprintf('retcode: %s, selector: %s', $retcode, $selector));
            }

            if (in_array($retcode,['1100','1101'])) {
                $this->_echo('[*] 你在手机上或者其他地方登出了微信，债见');
                break;
            }elseif ($retcode == '0') {
                if ($selector == '2' || $selector == '3') {
                    $r = $this->webwxsync();
                    if ($r) {
                        $this->handleMsg($r);
                    }
                } elseif ($selector == '4') {//朋友圈有动态
                    $this->_echo(sprintf('[*] 朋友圈有动态'));
                    $r = $this->webwxsync();
                    if ($r) {
                        file_put_contents(\Yii::$app->basePath . "/runtime/wechat/msg/pengyouquan.json", var_export($r, true), FILE_APPEND);
                        $this->handleMsg($r);
                    }
                } elseif ($selector == '6') {//有消息返回结果
                    # 通过好友验证
                    $r = $this->webwxsync();
                    if ($r) {
                        file_put_contents(\Yii::$app->basePath . "/runtime/wechat/msg/yanzheng.json", var_export($r, true), FILE_APPEND);
                        $this->handleMsg($r);
                    }
                } elseif ($selector == '7') {
                    continue;
                    $playWeChat += 1;
                    $this->_echo(sprintf('[*] 你在手机上玩微信被我发现了 %d 次', $playWeChat));
                    $r = $this->webwxsync();
                    if ($r) {
                        file_put_contents(\Yii::$app->basePath . "/runtime/wechat/msg/wanweixin.json", var_export($r, true), FILE_APPEND);
                        $this->handleMsg($r);
                    }
                } elseif ($selector == '0') {
                    sleep(1);
                }
            }
            if ((time() - $this->lastCheckTs) <= 5) {
                sleep(time() - $this->lastCheckTs);
            }
        }
    }


    public function handleMsg($r)
    {
        foreach ($r['AddMsgList'] as $msg) {
            $this->_echo('[*] 新的消息 type:'.$msg['MsgType'].'，请注意查收');

            $msgType = $msg['MsgType'];
            $name = $this->getUserRemarkName($msg['FromUserName']);
            $content = $msg['Content'] = self::br2nl(html_entity_decode($msg['Content']));

            if ($msgType == 1) {
                //lbbniu 重要
                if ($this->autoReplyMode) {
                    if (substr($msg['FromUserName'], 0, 2) == '@@' && stripos($content, ':' . PHP_EOL/*":<br/>"*/) !== false) {
                        list($people, $content) = explode(':' . PHP_EOL/*":<br/>"*/, $content);
                        //continue;
                    }
                    //自己发的消息不自动回复
                 if ($msg['FromUserName'] == $this->User['UserName']) return ;


                    #只有在群里@我才恢复
                    echo $msg['FromUserName']."\r\n";
                    echo $content."\r\n";
                    if(substr($msg['FromUserName'], 0, 2) == '@@' && strstr($content, "@夏天robot") !== false){
                        $toolinJson = CTools::tuling(['info' => $content]);
                        $content  =  $toolinJson['text'];
                        if(!empty($toolinJson['url'])) $content = $content.$toolinJson['url'];
                        $this->webwxsendmsg($content, $msg['FromUserName']);
                        $this->webwxsendshare($msg['FromUserName']);
                    }elseif(strpos($msg['FromUserName'], '@@') === false){
                        #单独聊天也回复

                        #拉入群聊
                        #用户
                        if($content == "9527") {
                            if($this->GroupList){
                                foreach($this->GroupList as $item){
                                    if($item['NickName'] == "机器人夏天测试群"){
                                        $chatRoomKehuId = $item['UserName'];
                                        break;
                                    }
                                }
                                $res =$this->webwxInviteChat($chatRoomKehuId,$msg['FromUserName']);
                                if($res) $this->webwxsendmsg("欢迎新人:".$msg['NickName'],$chatRoomKehuId);
                            }
                            return;
                        }

                        #开发
                        if($content == "007") {
                            if($this->GroupList){
                                foreach($this->GroupList as $item){
                                    if($item['NickName'] == "机器人夏天交流群"){
                                        $chatRoomKaifaId = $item['UserName'];
                                        break;
                                    }
                                }
                                $res =$this->webwxInviteChat($chatRoomKaifaId,$msg['FromUserName']);
                                if($res) $this->webwxsendmsg("欢迎新人:".$msg['NickName'],$chatRoomKaifaId);
                            }
                            return;
                        }

                        #图灵机器人
                        $toolinJson = CTools::tuling(['info' => $content]);
                        $content  =  $toolinJson['text'];
                        if(!empty($toolinJson['url'])) $content = $content.$toolinJson['url'];
                        $this->webwxsendmsg($content, $msg['FromUserName']);
                    }else{
                        return ;
                    }
                    $this->_echo($name.'：'.$content);

                }
            } elseif ($msgType == 3) {
                $this->_echo($name.' 发送了一张图片');
                continue;
                if ($this->webwxsendmsg("收到您的图片了", $msg['FromUserName'])) {
                    $this->_echo('自动回复:成功\r\n');
                } else {
                    $this->_echo('自动回复失败\r\n');
                }
            }elseif($msgType == 37){
                //是否自动通过加好友验证

                $verifyMsg =  $msg['RecommendInfo']['Content'];
                $this->_echo(sprintf('%s 请求加您为好友' , $msg['RecommendInfo']['NickName']));
                $this->_echo(sprintf('验证信息 %s' , $msg['RecommendInfo']['Content']));
                #根据验证内容选择是否加入群聊中
                if(true){
                    $data = [
                        "Value" => $msg['RecommendInfo']['UserName'],
                        "VerifyUserTicket" => $msg['RecommendInfo']['Ticket']
                    ];
                    if($this->webwxverifyuser($data,3)){
                        $this->_echo(sprintf('添加 %s 好友成功' , $msg['RecommendInfo']['NickName']));
                        $this->webwxsendmsg("您好,我是机器人夏天", $msg['RecommendInfo']['UserName']);


                    }


                }

            }elseif ($msgType == 10002) {//撤销消息
                $this->_echo(sprintf('%s 撤回了一条消息', $name)."r\n");
                if ($this->webwxsendmsg(sprintf('%s 撤回了一条消息', $name), $msg['FromUserName'])) {
                    $this->_echo('自动回复:成功\r\n');
                } else {
                    $this->_echo('自动回复失败\r\n');
                }
            }elseif($msgType == 49 && $msg['AppMsgType'] == 5){
                var_dump($msg);
                $this->_echo("收到分享 \r\n");
                $this->webwxsendmsg("发送分享", $msg['FromUserName']);
                $this->webwxsendshare();

            }

            usleep(300000);
        }
    }

    public function synccheck()
    {
        $params = [
            'r' => time(),
            'sid' => $this->sid,
            'uin' => $this->uin,
            'skey' => $this->skey,
            'deviceid' => $this->deviceId,
            'synckey' => $this->synckeystr,
            '_' => time(),
        ];
        $url = $this->sync_url.'/synccheck?' . http_build_query($params);
        $data = $this->_curlGet($url);
        var_dump($data);
        if (preg_match('/window.synccheck={retcode:"(\d+)",selector:"(\d+)"}/', $data, $pm)) {
            $retcode = $pm[1];
            $selector = $pm[2];
        } else {

            $retcode = -1;
            $selector = -1;
        }
        return [$retcode, $selector];
    }


    public function webwxsync()
    {

        $url = sprintf($this->base_uri . '/webwxsync?sid=%s&skey=%s&pass_ticket=%s', $this->sid, $this->skey, $this->pass_ticket);
        $params = [
            'BaseRequest' => $this->BaseRequest,
            'SyncKey' => $this->SyncKey,
            'rr' => time()
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);
        if ($this->DEBUG) var_dump($dic);

        if ($dic['BaseResponse']['Ret'] == 0) {
            $this->SyncKey = $dic['SyncKey'];
            $synckey = [];
            if (!empty($this->SyncKey['List'])) {
                foreach ($this->SyncKey['List'] as $keyVal) {
                    $synckey[] = "{$keyVal['Key']}_{$keyVal['Val']}";
                }

                $this->synckeystr = implode('|', $synckey);
            }

        }
        return $dic;
    }

    private function _showQRCodeImg()
    {
//        $url = 'https://login.weixin.qq.com/qrcode/' . $this->weuuid;
//        $params = [
//            't' => 'webwx',
//            '_' => time()
//        ];
////
////
//        $data = $this->_curlGet($url, $params);
//        $this->_saveFile('qrcode.jpg', $data, '_showQRCodeImg');
        //os.startfile(QRCODE_PATH)
        //T命令行显示
        $this->cmdqrcode("https://login.weixin.qq.com/l/".$this->weuuid);
    }

    private function _initUuid()
    {
        $url = 'https://login.wx.qq.com/jslogin';
        $params = [
            'appid' => $this->appid,
            //'redirect_uri'=> $this->redirect_uri,
            'fun' => 'new',
            'lang' => $this->lang,
            '_' => time(),
        ];
        $data = $this->_curlGet($url, $params);
        $regx = '/window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"/';
        if (preg_match($regx, $data, $pm)) {
            $code = $pm[1];
            $this->weuuid = $pm[2];
            return $code == '200';
        }
        return false;
    }





    public function _saveFile($filename, $data, $api = null)
    {
        $fn = $filename;
        if (isset($this->saveSubFolders[$api])) {
            $dirName = $this->saveFolder . $this->saveSubFolders[$api];
            umask(0);
            if (!is_dir($dirName)) {
                mkdir($dirName, 0777, true);
                chmod($dirName, 0777);
            }
            $fn = $dirName . '/' . $filename;
            $this->_echo(sprintf('Saved file: %s', $fn));
            //file_put_contents($fn, $data);
            $f = fopen($fn, 'wb');
            if ($f) {
                fwrite($f, $data);
                fclose($f);
            } else {
                $this->_echo('[*] 保存失败 - ' . $fn);
            }
        }
        return $fn;
    }

    public function _echo($data)
    {
        if (is_string($data)) {
            echo $data . "\n";
        } elseif (is_array($data)) {
            print_r($data);
        } elseif (is_object($data)) {
            var_dump($data);
        } else {
            echo $data;
        }
    }


    /**
     * 发送消息
     * @param $word
     * @param string $to
     * @return bool
     */
    public function webwxsendmsg($word, $to = 'filehelper')
    {


        $url = sprintf($this->base_uri .
            '/webwxsendmsg?pass_ticket=%s', $this->pass_ticket);
        $clientMsgId = (time() * 1000) . substr(uniqid(), 0, 5);
        $params = [
            'BaseRequest' => $this->BaseRequest,
            'Msg' => [
                "Type" => 1,
                "Content" => $word,
                "FromUserName" => $this->User['UserName'],
                "ToUserName" => $to,
                "LocalID" => $clientMsgId,
                "ClientMsgId" => $clientMsgId
            ]
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);
        return $dic['BaseResponse']['Ret'] == 0;
    }


    public function webwxInviteChat($chatId,$to='filehelper'){
        $url = sprintf($this->base_uri .
            '/webwxupdatechatroom?fun=addmember');
        $params = [
            'BaseRequest' => $this->BaseRequest,
            'ChatRoomName' => $chatId,
            'AddMemberList' => $to
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);
        return $dic['BaseResponse']['Ret'] == 0;
    }

    /**
     * 分享
     * @param $word
     * @param string $to
     * @return bool
     */
    public function webwxsendshare($to = 'filehelper')
    {


        $url = sprintf($this->base_uri .
            '/webwxsendappmsg?pass_ticket=%s', $this->pass_ticket);
        $clientMsgId = (time() * 1000) . substr(uniqid(), 0, 5);
        $params = [
            'BaseRequest' => $this->BaseRequest,
            'Msg' => [
                'Type' => 49,
                'Content' => '测试',
                "FromUserName" => $this->User['UserName'],
                "ToUserName" => $to,
                "LocalID" => $clientMsgId,
                "ClientMsgId" => $clientMsgId,
                "FileName" =>"测试",
                "Url" => "https://m.baidu.com"
            ]
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);
        return $dic['BaseResponse']['Ret'] == 0;
    }

    public function getUserRemarkName($id)
    {
        $name = substr($id, 0, 2) == '@@' ? '未知群' : '陌生人';
        if ($id == $this->User['UserName']) {
            return $this->User['NickName'];  # 自己
        }
        if (substr($id, 0, 2) == '@@') {
            # 群
            $name = $this->getGroupName($id);
        } else {
            # 特殊账号
            foreach ($this->SpecialUsersList as $member) {
                if ($member['UserName'] == $id) {
                    $name = $member['RemarkName'] ? $member['RemarkName'] : $member['NickName'];
                }
            }
            # 公众号或服务号
            foreach ($this->PublicUsersList as $member) {
                if ($member['UserName'] == $id) {
                    $name = $member['RemarkName'] ? $member['RemarkName'] : $member['NickName'];
                }
            }
            # 直接联系人
            foreach ($this->ContactList as $member) {
                if ($member['UserName'] == $id) {
                    $name = $member['RemarkName'] ? $member['RemarkName'] : $member['NickName'];
                }
            }
            # 群友
            foreach ($this->GroupMemeberList as $member) {
                if ($member['UserName'] == $id) {
                    $name = $member['DisplayName'] ? $member['DisplayName'] : $member['NickName'];
                }
            }
        }
        if ($name == '未知群' || $name == '陌生人') {
            var_dump($id);
        }
        return $name;
    }

    public function getGroupName($id)
    {
        $name = '未知群';
        foreach ($this->GroupList as $member) {
            if ($member['UserName'] == $id) {
                $name = $member['NickName'];
            }
        }
        if ($name == '未知群') {
            # 现有群里面查不到
            $GroupList = $this->getNameById($id);
            foreach ($GroupList as $group) {
                $this->GroupList[] = $group;
                if ($group['UserName'] == $id) {
                    $name = $group['NickName'];
                    $MemberList = $group['MemberList'];
                    foreach ($MemberList as $member)
                        $this->GroupMemeberList[] = $member;
                }
            }
        }
        return $name;
    }

    public function getNameById($id)
    {
        $url = sprintf($this->base_uri .
            '/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s',
            time(), $this->pass_ticket);
        $params = [
            'BaseRequest' => $this->BaseRequest,
            "Count" => 1,
            "List" => [["UserName" => $id, "EncryChatRoomId" => ""]]
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);

        # blabla ...
        return $dic['ContactList'];
    }

    /**
     * 添加好友，或者通过好友验证消息
     * @Opcode 2 添加 3 通过
     */
    public function webwxverifyuser($user,$Opcode){
        $url = sprintf($this->base_uri.'/webwxverifyuser?lang=zh_CN&r=%s&pass_ticket=%s' ,time()*1000, $this->pass_ticket);

        $params = [
            "BaseRequest"=> $this->BaseRequest,
            "Opcode"=>3,
            "VerifyUserListSize"=>1,
            "VerifyUserList"=>[$user],
            "VerifyContent"=>"",
            "SceneListCount"=>1,
            "SceneList"=>[33],
            "skey"=>$this->skey
        ];
        $dic = CHttpWechat::curlPostJson($url, ['cookie' => $this->cookie,'user_agent' => $this->user_agent],$params);
        if ($this->DEBUG)
            var_dump($dic);
        return $dic['BaseResponse']['Ret'] == 0;
    }

}
